#include "at32f435_437_board.h"
#include "at32f435_437_clock.h"

#include "FreeRTOS.h"
#include "task.h"
#include "event_groups.h"

#include "rtos_bsp.h"

#include "u8g2_hal.h"
#include "u8g2.h"

#include "llcc68.h"
#include "llcc68_drive.h"

#define LED_ORANGE_ON()		gpio_bits_set(GPIOB, GPIO_PINS_12);
#define LED_ORANGE_OFF()	gpio_bits_reset(GPIOB, GPIO_PINS_12);

#define LED_GREEN_ON()		gpio_bits_set(GPIOB, GPIO_PINS_13);
#define LED_GREEN_OFF()		gpio_bits_reset(GPIOB, GPIO_PINS_13);

EventGroupHandle_t xLLCC68EventGroup;
u8g2_t u8g2;

extern i2c_handle_type hi2cB;

void u8g2_disp_init(void)
{
	u8g2_i2c_init();
	u8g2_Setup_ssd1306_i2c_128x64_noname_f(
			&u8g2,
			U8G2_R0,
			u8x8_byte_i2c,
			u8x8_gpio_and_delay);  // init u8g2 structure
	u8x8_SetI2CAddress(&u8g2.u8x8, 0x78);

	u8g2_InitDisplay(&u8g2); // send init sequence to the display, display is in sleep mode after this,
	u8g2_SetContrast(&u8g2, 0xff);
	u8g2_SetPowerSave(&u8g2, 0); // wake up display
	u8g2_ClearBuffer(&u8g2);
	u8g2_ClearDisplay(&u8g2);
}

void llcc68_rx_task(void *pvParameters)
{
	uint32_t temp = 0;
	char tmr_buf1[32];
	
	xLLCC68EventGroup = xEventGroupCreate();
	
	llcc68_chip_init();
	llcc68_set_tx_cfg(0xff);
	
	while(1)
	{
		LED_ORANGE_OFF();
		
		EventBits_t uxBits;
		uxBits = xEventGroupWaitBits(
					xLLCC68EventGroup,   /* The event group being tested. */
					DIO_DONE_BIT, /* The bits within the event group to wait for. */
					pdTRUE,        /* BIT_0 & BIT_4 should be cleared before returning. */
					pdFALSE,       /* Don't wait for both bits, either bit will do. */
					portMAX_DELAY );/* Wait a maximum of 100ms for either bit to be set. */
		
		if(uxBits & DIO_DONE_BIT)
		{
			llcc68_irq_mask_t llcc68_irq_mask;
			llcc68_get_and_clear_irq_status(NULL, &llcc68_irq_mask);
			
			// rx done
			if(llcc68_irq_mask & IRQ_RX_DONE_BIT){
				LED_ORANGE_ON();
			
				llcc68_rx_buffer_status_t llcc68_rx_buffer_status;
				llcc68_get_rx_buffer_status(NULL, &llcc68_rx_buffer_status);
				
				//printf("%X,%X\r\n",llcc68_rx_buffer_status.buffer_start_pointer, llcc68_rx_buffer_status.pld_len_in_bytes);
				uint8_t red_buf[255];
				red_buf[llcc68_rx_buffer_status.pld_len_in_bytes] = '\0';
				llcc68_read_buffer(NULL, llcc68_rx_buffer_status.buffer_start_pointer, red_buf, llcc68_rx_buffer_status.pld_len_in_bytes);
				//uart_printf_rtos("%s\r\n", red_buf);
				
				llcc68_pkt_status_lora_t llcc68_pkt_status_lora;
				llcc68_get_lora_pkt_status(NULL, &llcc68_pkt_status_lora);
				
				char pkt_buf[32];
				char pkt_buf1[32];
				char pkt_buf2[32];
				sprintf(pkt_buf, "rssi_pkt_in_dbm=%d", llcc68_pkt_status_lora.rssi_pkt_in_dbm);
				sprintf(pkt_buf1, "sig_dbm=%d", llcc68_pkt_status_lora.signal_rssi_pkt_in_dbm);
				sprintf(pkt_buf2, "snr_pkt_in_db=%d", llcc68_pkt_status_lora.snr_pkt_in_db);
				//uart_printf_rtos("rssi_pkt_in_dbm=%d,signal_rssi_pkt_in_dbm=%d,snr_pkt_in_db=%d\r\n",llcc68_pkt_status_lora.rssi_pkt_in_dbm,llcc68_pkt_status_lora.signal_rssi_pkt_in_dbm,llcc68_pkt_status_lora.snr_pkt_in_db);
				
				ertc_time_type time;
				ertc_calendar_get(&time);
				if(temp != time.sec)
				{
					sprintf(tmr_buf1, "%02d-%02d-%02d %02d:%02d:%02d",time.year, time.month, time.day,time.hour, time.min, time.sec);
					temp = time.sec;
				}
				
				u8g2_ClearBuffer(&u8g2);
				u8g2_SetFont(&u8g2, u8g2_font_6x13_tf);
				u8g2_DrawStr(&u8g2, 0, 13, (const char *)red_buf);
				u8g2_DrawStr(&u8g2, 0, 26, pkt_buf);
				u8g2_DrawStr(&u8g2, 0, 39, pkt_buf1);
				u8g2_DrawStr(&u8g2, 0, 52, pkt_buf2);
				u8g2_DrawStr(&u8g2, 0, 64, tmr_buf1);
				u8g2_SendBuffer(&u8g2);
			
				llcc68_rx();
			}
			if(llcc68_irq_mask & IRQ_HEADER_ERR_BIT)
			{
				uart_printf_rtos("HEADER_ERR\r\n");
			}
			if(llcc68_irq_mask & IRQ_CRC_ERR_BIT){
				uart_printf_rtos("CRC_ERR\r\n");
			}
//			if(llcc68_irq_mask & IRQ_PREAMBLE_DETECTED_BIT){
//				uart_printf_rtos("PREAMBLE_DETECTED\r\n");
//			}
//			if(llcc68_irq_mask & IRQ_SYNC_WORD_VALID_BIT){
//				uart_printf_rtos("SYNC_WORD_VALID\r\n");
//			}
			if(llcc68_irq_mask & IRQ_HEADER_VALID_BIT){
				//uart_printf_rtos("HEADER_VALID\r\n");
			}
		}
	}
	
	vTaskDelete(NULL);
}

void led_flashing_task(void *pvParameters)
{
	gpio_init_type gpio_initstruct;
	crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
	
	gpio_default_para_init(&gpio_initstruct);
	gpio_initstruct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	gpio_initstruct.gpio_mode = GPIO_MODE_OUTPUT;
	gpio_initstruct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
	gpio_initstruct.gpio_pins = GPIO_PINS_12 | GPIO_PINS_13;
	gpio_initstruct.gpio_pull = GPIO_PULL_NONE;
	
	gpio_init(GPIOB, &gpio_initstruct);
	LED_GREEN_ON();
	
//	while(1)
//	{
//		gpio_bits_write(GPIOB, GPIO_PINS_12, !gpio_output_data_bit_read(GPIOB, GPIO_PINS_12));
//		vTaskDelay(pdMS_TO_TICKS(100));
//		gpio_bits_write(GPIOB, GPIO_PINS_13, !gpio_output_data_bit_read(GPIOB, GPIO_PINS_13));
//		vTaskDelay(pdMS_TO_TICKS(100));
//	}
	vTaskDelete(NULL);
}

void app_main(void *pvParameters)
{
	u8g2_disp_init();
	
	eeprom_i2c_init();
	uint32_t rx_buf_boot_time;
	i2c_memory_read_dma(&hi2cB, I2C_MEM_ADDR_WIDIH_8, I2CB_ADDRESS, 0x00, (uint8_t *)&rx_buf_boot_time, 4, I2C_TIMEOUT);
	i2c_wait_end(&hi2cB, I2C_TIMEOUT);
	// inc boot time
	rx_buf_boot_time++;
	i2c_memory_write_dma(&hi2cB, I2C_MEM_ADDR_WIDIH_8, I2CB_ADDRESS, 0x00, (uint8_t *)&rx_buf_boot_time, 4, I2C_TIMEOUT);
	i2c_wait_end(&hi2cB, I2C_TIMEOUT);
	uart_printf("BOOT TIME: %d\r\n", rx_buf_boot_time);
	
	char boot_time_fmt[32];
	sprintf(boot_time_fmt, "BOOT TIME: %d", rx_buf_boot_time);
	
	u8g2_ClearBuffer(&u8g2);
	u8g2_SetFont(&u8g2, u8g2_font_6x13_tf);
	u8g2_DrawStr(&u8g2, 0, 26, "System Started");
	u8g2_DrawStr(&u8g2, 0, 36, boot_time_fmt);
	u8g2_SendBuffer(&u8g2);
	vTaskDelay(pdMS_TO_TICKS(3000));
	
	xTaskCreate(llcc68_rx_task, "app_main", 1024 * 2, NULL, 1, NULL);
	xTaskCreate(led_flashing_task, "led_flashing_task", 512, NULL, 1, NULL);
	vTaskDelete(NULL);
}

/**
  * @brief  main function.
  * @param  none
  * @retval none
  */
int main(void)
{
	qspi_xip_config();
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
  system_clock_config();

  //at32_board_init();
	uart_print_init(115200);
	uart_print_dma_init();
	delay_init_rtos();
	
	xTaskCreate(app_main, "app_main", 1024 * 8, NULL, 1, NULL);

	vTaskStartScheduler();
  while(1)
  {
  }
}

void vApplicationTickHook( void )
{
}

void vApplicationMallocFailedHook( void )
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c or heap_2.c are used, then the size of the
	heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
	FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
	to query the size of free heap space that remains (although it does not
	provide information on how the remaining heap might be fragmented). */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
	/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
	to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
	task.  It is essential that code added to this hook function never attempts
	to block in any way (for example, call xQueueReceive() with a block time
	specified, or call vTaskDelay()).  If the application makes use of the
	vTaskDelete() API function (as this demo application does) then it is also
	important that vApplicationIdleHook() is permitted to return to its calling
	function, because it is the responsibility of the idle task to clean up
	memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
	( void ) pcTaskName;
	( void ) pxTask;

	/* Run time stack overflow checking is performed if
	configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
	function is called if a stack overflow is detected. */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/